package com.hpe.springboot.springbootmybatis.controller;

import com.hpe.springboot.springbootmybatis.entity.User;
import com.hpe.springboot.springbootmybatis.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 用户控制器
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 转页面
    @RequestMapping("/{page}")
    public String toPage(@PathVariable("page") String page) {
        return page;
    }
    // 处理添加
    @PostMapping("/addHandler")
    public String add(User user) {
        userService.saveOrUpdate(user);
        return "list";
    }

    // 用户列表
    @GetMapping("/list")
    public String list(Model model) {
        List<User> users = userService.list();
        model.addAttribute("users", users);
        return "list";
    }

    // 转到修改页面
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "edit";
    }
    // 处理修改
    @PostMapping("/editHandler")
    public String edit(User user, String username) {
        user.setUsername(username);
        userService.saveOrUpdate(user);
        return "redirect:/user/list";
    }
}
